<?php
namespace app\admin\controller;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\Department as DepartmentModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;
use think\Session;
/**
 * 管理员管理
 * Class AdminUser
 * @package app\admin\controller
 */
class AdminUser extends AdminBase
{
    protected $admin_user_model;
    protected $department_model;
    protected $auth_group_model;
    protected $auth_group_access_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->admin_user_model        = new AdminUserModel();
        $this->department_model        = new DepartmentModel();
        $this->auth_group_model        = new AuthGroupModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();

        //部门
        $department_list 	=	$this->department_model->order(['sort' => 'DESC', 'id' => 'DESC'])->select();
        $this->assign('department_list', $department_list);

        //用户组
        $auth_group_list = $this->auth_group_model->select();
        $this->assign('auth_group_list', $auth_group_list);

    }

    /**
     * 管理员管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($cleanup = "",$did = "",$gid = "",$keyword = "", $page = 1 ,$list_rows = 15)
    {
        //定义查询
        if ($cleanup) {
            Session::delete('did');
            Session::delete('gid');
            Session::delete('keyword');
        }
        if ($did || $gid || $keyword) {
            Session::delete('did');
            Session::set('did',$did);
            Session::delete('gid');
            Session::set('gid',$gid);
            Session::delete('keyword');
            Session::set('keyword',$keyword);
        }

        $where = [];

        //部门
        if (Session::get('did')) {
            $where['did']  = Session::get('did');
        }

        //权限组
        if (Session::get('gid')) {
            $where['group_id'] = Session::get('gid');
        }

        if (Session::get('keyword')) {
            $where['username|name|mobile'] = ['like', "%".Session::get('keyword')."%"];
        }
        $admin_user = Db::view('auth_group_access','group_id')
            ->view('auth_group',
                'title','auth_group.id=auth_group_access.group_id')
            ->view('admin_user',
                'id,username,did,img,name,mobile,email,address,status,create_time,update_time',
                'admin_user.id=auth_group_access.uid')
            ->where($where)->order('id DESC')->paginate($list_rows, false, ['page' => $page]);
        $admin_user_list=[];
        foreach($admin_user as $key => $value) {
            $value['department'] = $this->department_model->find($value['did']);
            $admin_user_list[]=$value;
        }

        return $this->fetch('index', [
            'admin_user' => $admin_user,
            'admin_user_list' => $admin_user_list,
            'did' => Session::get('did'),
            'gid' => Session::get('gid'),
            'keyword' => Session::get('keyword')
        ]);
    }

    /**
     * 添加管理员
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存管理员
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $data['username'] = $data['user_name'];
            $data['password'] = $data['pass_word'];
            $data['confirm_password'] = $data['confirm_pass_word'];
            $validate_result = $this->validate($data, 'AdminUser');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['password'] = md5($data['password'] . Config::get('salt'));
                if ($this->admin_user_model->allowField(true)->save($data)) {
                    $auth_group_access['uid']      = $this->admin_user_model->id;
                    $auth_group_access['group_id'] = $data['group_id'];
                    $this->auth_group_access_model->save($auth_group_access);
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑管理员
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $admin_user             = $this->admin_user_model->find($id);
        $auth_group_access      = $this->auth_group_access_model->where('uid', $id)->find();
        $admin_user['group_id'] = $auth_group_access['group_id'];

        return $this->fetch('edit', ['admin_user' => $admin_user]);
    }

    /**
     * 更新管理员
     * @param $id
     */
    public function update($id,$status)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $data['username'] = $data['user_name'];
            $data['password'] = $data['pass_word'];
            $data['confirm_password'] = $data['confirm_pass_word'];
            $validate_result = $this->validate($data, 'AdminUser');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $admin_user              = $this->admin_user_model->find($id);
                $admin_user->id          = $id;
                $admin_user->username    = $data['username'];
                $admin_user->img         = $data['img'];
                $admin_user->name        = $data['name'];
                $admin_user->mobile      = $data['mobile'];
                $admin_user->email       = $data['email'];
                $admin_user->address     = $data['address'];
                $admin_user->did         = $data['did'];
                $admin_user->status      = $data['status'];
                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $admin_user->password = md5($data['pass_word'] . Config::get('salt'));
                }
                if ($admin_user->save() !== false) {
                    $auth_group_access['uid']      = $id;
                    $auth_group_access['group_id'] = $data['group_id'];
                    $this->auth_group_access_model->where('uid', $id)->update($auth_group_access);
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }else{
            if ($id == 1 && $status != 1) {
                $this->error('默认管理员不可禁用');
            }
            $admin_user              = $this->admin_user_model->find($id);
            $admin_user->id          = $id;
            $admin_user->status   = $status;
            if ($admin_user->save() !== false) {
                $this->success('状态更新成功');
            } else {
                $this->error('状态更新失败');
            }
        }
    }

    /**
     * 删除管理员
     * @param $id
     */
    public function delete($id)
    {
        if ($id == 1) {
            $this->error('默认管理员不可删除');
        }
        if ($this->admin_user_model->destroy($id)) {
            $this->auth_group_access_model->where('uid', $id)->delete();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    
}
